package com.congee02.dbservlet.service.register;

import com.congee02.dbservlet.dao.UserDao;
import com.congee02.dbservlet.db.SingletonJdbcTemplate;
import com.congee02.dbservlet.entity.User;
import com.congee02.dbservlet.framework.ioc.annotation.Autowired;
import com.congee02.dbservlet.framework.ioc.annotation.Component;
import com.congee02.dbservlet.framework.jdbc.JdbcTemplate;
import com.congee02.dbservlet.result.Result;
import com.congee02.dbservlet.result.ResultFactory;
import com.congee02.dbservlet.utils.StringValidationUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;

@Component("registerService")
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserDao userDao;

    @Override
    public Result<?> register(String username, String pwd) {

        // case 1 : 用户名或者密码为空
        if (StringValidationUtils.isAnyNullOrBlank(username, pwd)) {
            return ResultFactory.failedResult("用户名和密码不能为空。");
        }

        JdbcTemplate template = SingletonJdbcTemplate.get();

        // case 2 : 已经存在重复的用户名
        try {
            if (userDao.isUserExist(username, template)) {
                return ResultFactory.failedResult("已有重复的用户名，请重新选择用户名。");
            }
        } catch (SQLException e) {
            return ResultFactory.failedResult("数据库错误，注册失败。");
        }


        boolean insertSuccess = true;
        String ew = null;
        try {
            User entity = new User(null, username, pwd);
            int affectedRows = userDao.insert(entity);
            if (affectedRows < 1) {
                insertSuccess = false;
            }
        } catch (SQLException e) {
            insertSuccess = false;
            ew = e.getMessage();
        }
        // case 3 : 数据库未知错误
        if (! insertSuccess) {
            return ResultFactory.failedResult("数据库错误，注册失败。" + ew);
        } else {
            // case 4 : 注册成功
            return ResultFactory.successResult("注册成功。");
        }
    }

    @Override
    public String toString() {
        return "RegisterServiceImpl{" +
                "userDao=" + userDao +
                '}';
    }
}
